<?php
/*
 * @奔跑的乌龟
 * @Date: 2020-12-30 16:41:01
 * @LastEditTime: 2020-12-31 22:06:54
 */
namespace app\index\model;

use think\Db;
use think\Model;
use think\facade\Session;

class Goods extends Model
{
    //  获取全部商品数据
    public function getAll(){
        return Goods::select();
    }
    
    //  分页获取商品数据
    public function getGoodList($page,$num=10){
        // $data = Goods::page($page,$num)->field('goods_id,goods_name,goods_price_min,sales_actual')->select();
        // $data = json_decode(json_encode($data),true);
        // for ($i = 0; $i < count($data); $i++) {
        //     $data[$i]["file_path"] = $this->getGoodPhoto($data[$i]["goods_id"]);
        // }
        // return $data;
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_price_min,g.sales_actual,min(u.file_path) FROM `yoshop_goods` `g` 
                INNER JOIN `yoshop_goods_image` `i` 
                ON `g`.`goods_id`=`i`.`goods_id` 
                INNER JOIN `yoshop_upload_file` `u` 
                ON `i`.`image_id`=`u` .`file_id`
            group by g.goods_id,g.goods_name";
        $data = Goods::query($sql);
        return $data;
    }
    
    //  根据商品Id查询商品
    public function getGood($gid){
        $good = Goods::where(["goods_id"=>$gid])->find();
        $good["file_path"] =  $this->getGoodAllPhoto($gid);
        return $good;
        
    }
    
    //  获取商品单张轮播图
    public function getGoodPhoto($gid){
        $imageId =  Db::table("yoshop_goods_image")->where(["goods_id"=>$gid])->value("image_id");
        return Db::table("yoshop_upload_file")->where(["file_id"=>$imageId])->value("file_path");
    }
    
    //  获取单个商品的全部轮播图
    public function getGoodAllPhoto($gid){
        
        $imageIdArray =  Db::table("yoshop_goods_image")->where(["goods_id"=>$gid])->field("image_id")->select();
        
        $res = array();
        
        for ($i = 0; $i < count($imageIdArray); $i++) {
            $arr = Db::table("yoshop_upload_file")->where(["file_id"=>$imageIdArray[$i]["image_id"]])->field('file_path')->select();
            $res[$i] = $arr;
        }
        return $res;
    }
    
}